package com.seeyon.apps.taxFund.event;


import cn.hutool.core.util.StrUtil;
import com.seeyon.apps.gkcwplugin.dao.DealDataDao;
import com.seeyon.apps.gkcwplugin.listener.FinanceListener;
import com.seeyon.apps.gkcwplugin.manager.SyncZDManager;
import com.seeyon.apps.gkcwplugin.po.ChailfPJPO;
import com.seeyon.apps.gkcwplugin.po.ChailfPO;
import com.seeyon.apps.gkcwplugin.po.ChailfSonPO;
import com.seeyon.apps.gkcwplugin.util.BaseConnection;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.Base64;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import com.seeyon.ctp.workflow.util.WorkflowEventConstants.WorkflowEventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 把生成凭证需要的信息写给浪潮数据库
 */
public class ChaiLvBaoXiaoPZEvent extends AbstractWorkflowEvent {

    private static final Logger logger = LoggerFactory.getLogger(FinanceListener.class);

    private final CAP4FormManager cap4FormManager;

    private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");

    private SyncZDManager syncZDManager = (SyncZDManager) AppContext.getBean("syncZDManager");

    private DealDataDao dealDataDao = (DealDataDao) AppContext.getBean("dealDataDao");

    public ChaiLvBaoXiaoPZEvent(CAP4FormManager cap4FormManager) {
        this.cap4FormManager = cap4FormManager;
    }


    @Override
    public ApplicationCategoryEnum getAppName() {
        // TODO 自动生成的方法存根
        return ApplicationCategoryEnum.form;
    }

    @Override
    public WorkflowEventType getType() {
        // TODO 自动生成的方法存根
        return WorkflowEventType.Ext;
    }

    @Override
    public String getId() {
        return "ChaiLvBaoXiaoPZEvent";
    }

    @Override
    public String getLabel() {
        return "差旅报销生成凭证";
    }

    /*
     * 流程发起前事件
     *
     */
    @Override
    public synchronized WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
        logger.info("=========================进入-差旅报销凭证生成-onBeforeStart=============================");



        WorkflowEventResult res = new WorkflowEventResult();
        Long memberId = AppContext.getCurrentUser().getId();
        long affairId = data.getAffairId();

        Map<String, Object> map = data.getBusinessData();
        //获取表单的数据
        FormDataMasterBean master = (FormDataMasterBean) map.get("formDataBean");
        Long formId = master.getFormTable().getFormId();
        Long formRecordId = master.getId();

        // url地址拼接


        String url = "/seeyon/collaboration/collaboration.do?method=summary&openFrom=listSent&affairId="
                + affairId;
        String urlCode = null;
        try {
            V3xOrgMember member = orgManager.getMemberById(memberId);

            String ticket = Base64.encodeString(member.getCode());
            logger.info("--------------------------ticket:" + ticket);
            url = "http://114.218.158.106:8801/seeyon/login/sso?from=sample&ticket=" + ticket + "&tourl="
                    + URLEncoder.encode(url, "UTF-8");
            urlCode = URLEncoder.encode(url, "UTF-8");

            logger.info("--------------------------url:" + url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("差旅报销凭证回写失败：{}", e.getMessage());
        } catch (BusinessException e) {
            e.printStackTrace();
            logger.error("差旅报销凭证回写失败：{}", e.getMessage());
        }

        ChailfPO chailfPO = dealDataDao.findChailfPOById(Long.valueOf(formRecordId));
        List<ChailfPJPO> pjList = dealDataDao.findChailfPJPO(Long.valueOf(formRecordId));
        List<ChailfSonPO> sonList = dealDataDao.findChailfSonPO(Long.valueOf(formRecordId));
//				List<ChailfBankPO> bankList = dealDataDao.findChailfBankPO(Long.valueOf(formRecordId));

        for (ChailfSonPO row : sonList) {
            if (row.getYhhd() == null || "".equals(row.getYhhd().toString())) {
                res.setAlertMessage(StrUtil.format("【{}】异常【{}】", "发票开具申请", "获取表单数据为空"));
                logger.error("差旅报销表单yhhd数据为空");
            }
        }


        Connection conn = BaseConnection.getConnection();
        PreparedStatement ps = null;
        int rs = 0;

        try {
            logger.info("--------------------------主表插入开始");
            String zbSql = "INSERT INTO OAZJB_ZB (OAZJB_ZB_ID,OAZJB_ZB_BDLX,OAZJB_ZB_HSDW,"
                    + "OAZJB_ZB_BXBM,OAZJB_ZB_SQRQ,OAZJB_ZB_FKSY,OAZJB_ZB_SFZX,OAZJB_ZB_HZJE,"
                    + "OAZJB_ZB_SQR,OAZJB_ZB_FKRQ,OAZJB_ZB_FKBM,OAZJB_ZB_FKDW,OAZJB_ZB_LSBH,OAZJB_ZB_LCDZ,OAZJB_ZB_BY1)"
                    + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

            ps = conn.prepareStatement(zbSql);
            ps.setLong(1, chailfPO.getId());
            ps.setString(2, "2");
            ps.setString(3, chailfPO.getHsdw());
            ps.setString(4, chailfPO.getBxbm());
            if (chailfPO.getSqrq() != null) {
                java.sql.Date sqrq = new java.sql.Date(chailfPO.getSqrq().getTime());
                ps.setDate(5, sqrq);
            } else {
                ps.setDate(5, null);
            }
            ps.setString(6, chailfPO.getFksy());
            ps.setBigDecimal(7, chailfPO.getSfzx());
            ps.setBigDecimal(8, chailfPO.getHzje());
            ps.setString(9, chailfPO.getSqr());
            if (chailfPO.getFkrq() != null) {
                java.sql.Date fkrq = new java.sql.Date(chailfPO.getFkrq().getTime());
                ps.setDate(10, fkrq);
            } else {
                ps.setDate(10, null);
            }
            ps.setString(11, chailfPO.getFkbm());
            ps.setString(12, chailfPO.getFkdw());
            ps.setString(13, chailfPO.getLsbh());
            ps.setString(14, url);
            ps.setString(15, chailfPO.getXmbh());

            rs = ps.executeUpdate();

            if (rs == 0) {
                logger.info("差旅报销生成凭证 主表无更新数据");
                return null;
            }
            logger.info("--------------------------差旅报销生成凭证 主表插入结束");
            logger.info("--------------------------差旅报销生成凭证 票据表插入开始");
            for (ChailfPJPO row : pjList) {
                String pjSql = "INSERT INTO OAZJB_PJXX (OAZJB_PJXX_ID,OAZJB_PJXX_MXID,OAZJB_PJXX_FYRX,OAZJB_PJXX_FYBM,"
                        + "OAZJB_PJXX_RYR,OAZJB_PJXX_FYXM,OAZJB_PJXX_FYLX,OAZJB_PJXX_FLXMBH,OAZJB_PJXX_BXBZ,"
                        + "OAZJB_PJXX_PJRX,OAZJB_PJXX_KPMC,OAZJB_PJXX_XFSBM,OAZJB_PJXX_KPRQ,OAZJB_PJXX_JE,"
                        + "OAZJB_PJXX_SE,OAZJB_PJXX_SL,OAZJB_PJXX_KDJE,OAZJB_PJXX_HSJE,OAZJB_PJXX_FPDM,OAZJB_PJXX_FPBH)"
                        + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

                ps = conn.prepareStatement(pjSql);
                ps.setLong(1, row.getFormmainId());
                ps.setLong(2, row.getId());
                ps.setString(3, row.getFyrx());
                ps.setString(4, row.getFybm());
                ps.setString(5, row.getRyr());
                ps.setString(6, row.getFyxm());
                ps.setString(7, row.getFylx());
                ps.setString(8, row.getFlxmbh());
                ps.setString(9, row.getBxbz());
                ps.setString(10, row.getPjrx());
                ps.setString(11, row.getKpmc());
                ps.setString(12, row.getXfsbm());
                if (row.getKprq() != null) {
                    java.sql.Date kprq = new java.sql.Date(row.getKprq().getTime());
                    ps.setDate(13, kprq);
                } else {
                    ps.setDate(13, null);
                }
                ps.setBigDecimal(14, row.getJe());
                if (row.getSl() != null) {
                    ps.setBigDecimal(15, row.getSe());
                    if (row.getSl().contains("%")) {
                        int index = row.getSl().indexOf("%");
                        String sl = row.getSl().substring(0, index).trim();
                        BigDecimal divide = new BigDecimal(sl).divide(new BigDecimal(100));

                        ps.setString(16, divide.toString());
                    } else {
                        ps.setString(16, row.getSl());
                    }
                } else {
                    ps.setBigDecimal(15, BigDecimal.ZERO);
                    ps.setString(16, "0");
                }

                ps.setBigDecimal(17, row.getKdje());
                ps.setBigDecimal(18, row.getHsje());
                ps.setString(19, row.getFpdm());
                ps.setString(20, row.getFpbh());

                rs = ps.executeUpdate();

                if (rs == 0) {
                    logger.info("差旅报销生成凭证 票据表无更新数据");
                }
            }
            logger.info("--------------------------票据表插入结束");
            logger.info("--------------------------出纳表插入开始");
            for (ChailfSonPO row : sonList) {
                String cnSql = "INSERT INTO OAZJB_CNXX (OAZJB_CNXX_ID,OAZJB_CNXX_MXID,OAZJB_CNXX_XH,OAZJB_CNXX_ZFFS,"
                        + "OAZJB_CNXX_SKYH,OAZJB_CNXX_SKZH,OAZJB_CNXX_SKR,OAZJB_CNXX_ZFJE,OAZJB_CNXX_ZFSM,"
                        + "OAZJB_CNXX_CNFKYH,OAZJB_CNXX_CNFKZH)"
                        + "VALUES (?,?,?,?,?,?,?,?,?,?,?)";

                ps = conn.prepareStatement(cnSql);
                ps.setLong(1, row.getFormmainId());
                ps.setLong(2, row.getId());
                ps.setBigDecimal(3, row.getXh());
                ps.setString(4, row.getZffs());
                ps.setString(5, row.getSkyh());
                ps.setString(6, row.getSkzh());
                ps.setString(7, row.getSkr());
                ps.setBigDecimal(8, row.getZfje());
                ps.setString(9, row.getZfsm());
                ps.setString(10, row.getCnfkyh());
                ps.setString(11, row.getCnfkzh());

                rs = ps.executeUpdate();

                if (rs == 0) {
                    logger.info("差旅报销生成凭证 出纳表无更新数据");
                    return null;
                }
            }
            logger.info("--------------------------出纳表插入结束");
//					logger.info("--------------------------回单表插入开始");
//					for (ChailfBankPO row : bankList) {
//						String htSql = "INSERT INTO OAZJB_HTXX (OAZJB_HTXX_ID,OAZJB_HTXX_MXID,OAZJB_HTXX_XH,"
//								+ "OAZJB_HTXX_FKZH,OAZJB_HTXX_YHKD,OAZJB_HTXX_PZH)"
//								+ "VALUES (?,?,?,?,?,?)";
//
//						ps = conn.prepareStatement(htSql);
//						ps.setLong(1, row.getFormmainId());
//						ps.setLong(2, row.getId());
//						ps.setBigDecimal(3, row.getXh());
//						ps.setString(4, row.getFkzh());
//						ps.setString(5, row.getYhkd());
//						ps.setString(6, row.getPzh());
//
//						rs = ps.executeUpdate();
//
//						if (rs < 0) {
//							return;
//						}
//					}
//					logger.info("--------------------------回单表插入结束");
            logger.info("==========================结束-差旅报销凭证生成-onBeforeStart=============================");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}
